package com.jiulong.controller;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jdom.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSONObject;
import com.jiulong.bean.Order;
import com.jiulong.common.utils.ExportExcel;
import com.jiulong.common.utils.PayCommonUtil;
import com.jiulong.common.utils.PayConfigUtil;
import com.jiulong.common.utils.XMLUtil;
import com.jiulong.dao.TFavoriteMapper;
import com.jiulong.dao.TGiftMapper;
import com.jiulong.dao.TOrderMapper;
import com.jiulong.dao.TPayMapper;
import com.jiulong.dao.TProductMapper;
import com.jiulong.model.TAccount;
import com.jiulong.model.TFavorite;
import com.jiulong.model.TGift;
import com.jiulong.model.TIndexImg;
import com.jiulong.model.TIndexImgExample;
import com.jiulong.model.TIndexmenuExample;
import com.jiulong.model.TOrder;
import com.jiulong.model.TOrderExample;
import com.jiulong.model.TPay;
import com.jiulong.model.TPayExample;
import com.jiulong.model.TProduct;
import com.jiulong.service.AccountService;
import com.jiulong.service.OrderService;


@Controller
public class xkControl extends BaseController{

	@Autowired
	AccountService accountService;
	@Autowired
	TProductMapper tProductMapper;
	@Autowired
	TOrderMapper tOrderMapper;
	@Autowired
	TGiftMapper tGiftMapper;
	@Autowired
	TFavoriteMapper tFavoriteMapper;
	@Autowired
	TPayMapper TPayMapper;
	
	@Autowired
	com.jiulong.dao.TIndexImgMapper TIndexImgMapper;
	
	@RequestMapping("/order")
	public String order(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
		//String openid="ohx_wwiIXSM7yFNDcaLymiMeIh9o";
			HttpSession session = request.getSession();
		String openid=session.getAttribute("openid").toString();
		TAccount tAccount=	accountService.findAccountbyId(openid);
		System.out.println("我通过openid找到了用户的昵称！"+tAccount.getAccount());
		String account=tAccount.getAccount();
		String score=tAccount.getScore().toString();
		String rank=tAccount.getRank();
		model.addAttribute("rank", rank);
		model.addAttribute("score", score);
		model.addAttribute("account", account);	
		
		String productId= session.getAttribute("productId").toString();
		//String productId="10008";
		TProduct product =new TProduct();
		product= tProductMapper.selectByPrimaryKey(Integer.parseInt(productId));
		String productName=product.getName();
		String productIntroduce=product.getIntroduce();
		String imageUrl1=product.getPicture();
		String imageUrl="http://threeshop1.oss-cn-hangzhou.aliyuncs.com"+imageUrl1;
		model.addAttribute("productName", productName);
		model.addAttribute("productIntroduce", productIntroduce);
		model.addAttribute("account", account);	
		model.addAttribute("imageUrl", imageUrl);
		TOrder order=accountService.findOrderbyId(account);
		String amount=order.getAmount().toString();
	
		model.addAttribute("amount", amount);		
		return "order";
	}
	
	
	@RequestMapping("/huitiao")
	public String huitiao(HttpServletRequest request,HttpServletResponse response) throws IOException{
		System.out.println("我是回调的参数！");
		//读取参数
		InputStream inputStream ;
		StringBuffer sb = new StringBuffer();
		inputStream = request.getInputStream();
		String s ;
		BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
		while ((s = in.readLine()) != null){
			sb.append(s);
		}
		in.close();
		inputStream.close();

		//解析xml成map
		Map<String, String> m = new HashMap<String, String>();
		try {
			m = XMLUtil.doXMLParse(sb.toString());
		} catch (JDOMException e) {
			System.out.println("解析失败！");
			e.printStackTrace();
		}
		
		//过滤空 设置 TreeMap
		SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();		
		Iterator it = m.keySet().iterator();
		while (it.hasNext()) {
			String parameter = (String) it.next();
			String parameterValue = m.get(parameter);
			
			String v = "";
			if(null != parameterValue) {
				v = parameterValue.trim();
			}
			packageParams.put(parameter, v);
		}
		
		// 账号信息
        String key = PayConfigUtil.getKey(); // key
        String out_trade_no = (String)packageParams.get("out_trade_no");
        //logger.info(packageParams);
	    //判断签名是否正确
	    if(PayCommonUtil.isTenpaySign("UTF-8", packageParams,key)) {
	        //------------------------------
	        //处理业务开始
	        //------------------------------
	        String resXml = "";
	        if("SUCCESS".equals((String)packageParams.get("result_code"))){
	        	// 这里是支付成功

	        	String mch_id = (String)packageParams.get("mch_id");
	        	String openid = (String)packageParams.get("openid");
	        	String is_subscribe = (String)packageParams.get("is_subscribe");
	        	
	        	String bank_type = (String)packageParams.get("bank_type");
	        	String total_fee = (String)packageParams.get("total_fee");
	        	String transaction_id = (String)packageParams.get("transaction_id");    	
	        	System.out.println("mch_id:"+mch_id);
	        	System.out.println("openid:"+openid);
	        	System.out.println("is_subscribe:"+is_subscribe);
	        	System.out.println("out_trade_no:"+out_trade_no);
	        	System.out.println("total_fee:"+total_fee);
	        	System.out.println("bank_type:"+bank_type);
	        	
	        	//成功回调后需要处理预生成订单的状态和一些支付信息	
	        	//正常处理相关业务逻辑  
	        	//查询数据库中订单，首先判定订单中金额与返回的金额是否相等，不等金额被纂改  
	        	System.out.println("通过订单号开始查找");
	        	TOrder order=accountService.findOrderbytrade(out_trade_no);
	        	//String amount=order.getAmount().toString();
	        	//比较返回的金额
	        	// String total_fee1=String.valueOf((Double.valueOf(amount)*100));
	    	   //  String total_fee2 = total_fee1.substring(0,total_fee1.indexOf("."));
/*	    	     if(!total_fee2.equals(total_fee)){
	    	    	 System.out.println("金额被篡改，请联系技术人员！");
	    	    	 return "error";
	    	     }  */ 	
	    	     String payStatus=order.getPaystatus();
	    	     if(payStatus.equals("y")){
	    	    	 System.out.println("订单已被支付！");
	    	    	 return "error";
	    	     }
	    	     BigDecimal amount=new BigDecimal(total_fee); 
	    	     order.setFee(amount);
	    	     order.setPaystatus("y");
	    	     tOrderMapper.updateByPrimaryKeySelective(order);
	    	     System.out.println("更改后订单的状态是："+order.getPaystatus());
	         
	    	     try{
	    	    	    	 
	    	 		List favorite=accountService.findFavoritebytrade(out_trade_no);
	    	 		if(favorite.toString()!="[]"){
	    	 			 int gift_id=Integer.parseInt(((TFavorite) favorite.get(0)).getProductid());
		    	 	     tGiftMapper.deleteByPrimaryKey(gift_id);
		    	 	     System.out.println("删除了已使用的优惠券！  "+gift_id);
	    	 		}   
	    	 	}catch(Exception e){
	    	 		e.printStackTrace();
	    	 	}
	     System.out.println("删除已使用的优惠券有没哟偶被删除");
	    	   //判定订单是否已经被支付，不可重复支付 
	        	//优惠券数量减一
	        	System.out.println("transaction_id:"+transaction_id);	
	        	  resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
		                    + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
	        	
	        	
	        } else {
	        	System.out.println("支付失败,错误信息：" + packageParams.get("err_code")+
	        			            "-----订单号：：："+out_trade_no+"*******支付失败时间：：：："
	        			+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
	        	
	        	String err_code = (String)packageParams.get("err_code");

		            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
		                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
       
	        }
	        //------------------------------
	        //处理业务完毕
	        //------------------------------
	        BufferedOutputStream out = new BufferedOutputStream(
	                response.getOutputStream());
	        out.write(resXml.getBytes());
	        out.flush();
	        out.close();
	    } else{
	    	System.out.println("通知签名验证失败---时间::::"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
	    }
		return "index";
	}
	//从我的订单里面重新生成订单
	
	@RequestMapping(value="/checkChuanZhi" ,method=RequestMethod.POST)
	public String checkChuanZhi(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{

		String orderId=request.getParameter("orderId");
		if(orderId==null){
			return "error3";
		}
		System.out.println("我拿到了订单的id");
		String giftId1=request.getParameter("giftId");

		String giftprice=null;
		TGift gi=new TGift();
		if(giftId1!=null){
			try{
				int giftId=Integer.parseInt(giftId1);
			 gi=tGiftMapper.selectByPrimaryKey(giftId);
			  giftprice= String.valueOf(gi.getGiftprice())  ;
			 }catch(Exception e){
				 e.printStackTrace();
			 }
			
		}
	
		System.out.println("我拿到了折扣券的优惠");
		HttpSession session = request.getSession();
		//String openid="ohx_wwiIXSM7yFNDcaLymiMeIh8o";
		String openid=	session.getAttribute("openid").toString();
		System.out.println("我拿到了openid");
		TOrder order=new TOrder();
		   //生成订单号
					long currentTimeMillis = System.currentTimeMillis();
				    String strReq =  currentTimeMillis + "jiulongWei";
				    String out_trade_no = strReq; 
		order=tOrderMapper.selectByPrimaryKey(Integer.parseInt(orderId));
		String amount2=order.getAmount().toString();
		//修改订单的订单号
		 order.setRemark(out_trade_no);
	     tOrderMapper.updateByPrimaryKeySelective(order);
		double a;
		if(giftprice!=null){
		
			a=	Double.parseDouble(amount2)-Double.parseDouble(giftprice);
			a=Math.round(a*100)/100.00;
		}else{
			a=Double.parseDouble(amount2);
		}
		String amount1=String.valueOf(a);
	//上图找到了时间
	
				
		String total_fee1=String.valueOf((Double.valueOf(amount1)*100));
	     String total_fee = total_fee1.substring(0,total_fee1.indexOf("."));
	     System.out.println("我拿到了最终的生成价格的价格");
	
		String js = null;
		try {
			js = weixin_pay.weixin_pay(openid,total_fee,out_trade_no);
		} catch (Exception e) {
			System.out.println("预支付生成订单出错！");
			e.printStackTrace();
		}
		JSONObject jo=JSONObject.parseObject(js);
		model.addAttribute("appId", jo.get("appId"));
		model.addAttribute("timeStamp", jo.get("timeStamp"));
		model.addAttribute("nonceStr", jo.get("nonceStr"));
		model.addAttribute("package", jo.get("package"));
	    //model.addAttribute("packageValue", jo.get("packageValue"));    //这里用packageValue是预防package是关键字在js获取值出错
	    model.addAttribute("paySign", jo.get("paySign"));   
	    TAccount tAccount=	accountService.findAccountbyId(openid);
		String score=tAccount.getScore().toString();
		String rank=tAccount.getRank();
		String nickname=tAccount.getNickname();
		String imageUrl=order.getExpressno();
		String productName=order.getExpresscode();
		String productIntroduce=order.getExpressname();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		String date=df.format(new Date());
		model.addAttribute("time", date);
		model.addAttribute("orderId", orderId);
		model.addAttribute("rank", rank);
		model.addAttribute("score", score);
		model.addAttribute("account", nickname);	
		model.addAttribute("productName", productName);
		model.addAttribute("productIntroduce", productIntroduce);
		model.addAttribute("price", amount1);	
		model.addAttribute("imageUrl", imageUrl);
		System.out.println("神兽保佑，图片地址快快出来"+imageUrl);
		//植入销券记录
		
		if(giftId1!=null){
		try{
			TFavorite favorite=new TFavorite();
			favorite.setProductid(giftId1);
			favorite.setAccount(out_trade_no);
			tFavoriteMapper.insert(favorite);
		}catch(Exception e){
			e.printStackTrace();
		}
		}

		return "grzx";
	}

	
	
	@Autowired
	OrderService orderService;
	//进入订单页面未支付
	@RequestMapping("/selectOrder")
	public String selectOrder(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
		HttpSession session = request.getSession();
		//String openid=session.getAttribute("openid").toString();
		String openid="ohx_wwiIXSM7yFNDcaLymiMeIh9o";
		  TAccount tAccount=accountService.findAccountbyId(openid);
		  String account=tAccount.getAccount();
			String score=tAccount.getScore().toString();
			String rank=tAccount.getRank();
			String nickname=tAccount.getNickname();
			model.addAttribute("rank", rank);
			model.addAttribute("score", score);
			model.addAttribute("account", nickname);
			
			List gift=orderService.findGiftbyId(nickname);
			List list=orderService.findOrderDetailByOpenid(nickname);
		 model.addAttribute("detailList", list);
		 model.addAttribute("detailGift", gift);

		return "grzxDing";
	}
	
	//总部审核的订单页面
		@RequestMapping("/waitCheckdZong")
		public String waitCheckdZong(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
			
		//	String email=request.getParameter("email");
			//String username=request.getParameter("username");
		/*	String email="1";
			String username="shihui";
			//判断是否有审核的权限
			TUser user=accountService.findAccountByWaitCheckd(email,username);
			if(user==null){
				return "";
			}	
			*/
			String username="绥阳店";
			String dateBegin=request.getParameter("dateBegin");
			String dateEnd=request.getParameter("dateEnd");
			if(dateBegin==null||dateBegin.equals("")){
				dateBegin="2000-01-01";
				dateEnd="2020-0101";
			}
			List list = null;
			try{	
			
			//查询符合条件的订单数量
			TOrderExample example=new TOrderExample();
			example.createCriteria().andCarryEqualTo(0).andUserEqualTo(username).andPaystatusEqualTo("y").andCreatedateBetween(dateBegin, dateEnd);   
	         long counts=tOrderMapper.countByExample(example);
	         HttpSession session=request.getSession();
	         session.setAttribute("counts", counts);
		    	 list=orderService.findOrderDetailWithNoCheck(username,dateBegin,dateEnd);
		}catch(Exception e){
			e.printStackTrace();
		}	
		    	
			 model.addAttribute("username", username);	
			 model.addAttribute("detailList", list);
			
		
			return "waitCheckdZong";
		}
	
	//待审核的订单页面
	@RequestMapping("/waitCheckd")
	public String waitCheckd(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
		 HttpSession session=request.getSession();
		 String username=session.getAttribute("username").toString();
		
		String dateBegin=request.getParameter("dateBegin");
		String dateEnd=request.getParameter("dateEnd");
		if(dateBegin==null||dateBegin.equals("")){
			dateBegin="2000-01-01";
			dateEnd="2020-0101";
		}
		List list = null;
		//查询符合条件的订单数量
		TOrderExample example=new TOrderExample();
		
		example.createCriteria().andUserEqualTo(username).andPaystatusEqualTo("y").andCreatedateBetween(dateBegin, dateEnd); 
		 long counts=tOrderMapper.countByExample(example);
		 session.setAttribute("counts", counts);
		 TPay pay=TPayMapper.selectByPrimaryKey(2);
		 String payLi=pay.getSeller();
		 double payLi1=Double.parseDouble(payLi);  
		try{	
			list=orderService.findOrderDetailWithNoCheck(username,dateBegin,dateEnd);
	}catch(Exception e){
		e.printStackTrace();
	}	
	    	
		String total=orderService.findOrderDetailWithNoCheck1(username,dateBegin,dateEnd,counts);
		model.addAttribute("total", total);
		model.addAttribute("payLi1", payLi1);
		 model.addAttribute("username", username);	
		 model.addAttribute("detailList", list);
		
	
		return "waitCheckd";
	}
	//订单审核提交
		@RequestMapping(value="/orderCheckCommit" ,method=RequestMethod.POST)
		public String indexPcLogin(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
			
			HttpSession session=request.getSession(); 
			String count=session.getAttribute("counts").toString();
			int counts=Integer.parseInt(count);
			 TOrder order=new TOrder();
			 long currentTimeMillis = System.currentTimeMillis();
			 String strReq =  currentTimeMillis + "jiulongOrder";
			 String out_trade_no = strReq;  
try{
	for(int i=0;i<counts;i++){
		String get="get"+i;
		get=request.getParameter(String.valueOf(i));	
		order=tOrderMapper.selectByPrimaryKey(Integer.parseInt(get));	
		order.setOtherrequirement(out_trade_no);
		tOrderMapper.updateByPrimaryKeySelective(order);	
	}
}catch(Exception e2){
	e2.printStackTrace();
}
//插入审核记录
TIndexImg ima=new TIndexImg();
ima.setTitle(order.getUser());
ima.setLink("账单待审核");

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
	String date=df.format(new Date());
ima.setDesc1(date);
ima.setPicture(out_trade_no);
TIndexImgMapper.insert(ima);	 

	    	return "waitCheckd";
		}
	
		
		//订单报表导出
	@RequestMapping(value="/orderExcelExport" ,method=RequestMethod.POST)
	public String orderExcelExport(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
					
					HttpSession session=request.getSession(); 
					String count=session.getAttribute("counts").toString();
					int counts=Integer.parseInt(count);
					 TOrder order=new TOrder();
					 ExportExcel e=new ExportExcel();	 
					List<Order> orderList=new ArrayList<Order>();
					
					TPay pay=TPayMapper.selectByPrimaryKey(2);
					String payLi=pay.getSeller();
					double payLi1=Double.parseDouble(payLi);
					double totalImport1 = 0;
					for(int i=0;i<counts;i++){
				String get="get"+i;
				get=request.getParameter(String.valueOf(i));
				order=tOrderMapper.selectByPrimaryKey(Integer.parseInt(get));
				//"分点信息","订单id", "房型","微信费率", "优惠金额", "单笔净盈利", "完成日期", "此次提交审核总盈利"
				String youHui1= order.getAmount().toString();
				String youHui2=order.getFee().toString();
				double youHui=Double.parseDouble(youHui1)-Double.parseDouble(youHui2)/100.00;
				String single=(order.getFee()).toString();	
				BigDecimal   b   =   new   BigDecimal(youHui);  
				double   f1   =   b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();  
		
				double totalImport=Double.parseDouble(single)*payLi1/100;
				orderList.add(new Order(order.getUser(),order.getId(),order.getExpressname(),payLi,f1,totalImport,new Date(),0.0));
				
				totalImport1+=totalImport;
			}
	
			 orderList.add(new Order("汇总金额",0,"0","0",0.0,0.0,new Date(),totalImport1));
			 try {
				 OutputStream out = new BufferedOutputStream(response.getOutputStream());
					e.test(orderList,out);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			 //报表导出成功执行页面跳转
			 
			 String username="绥阳店";
				String dateBegin=request.getParameter("dateBegin");
				String dateEnd=request.getParameter("dateEnd");
				if(dateBegin==null||dateBegin.equals("")){
					dateBegin="2000-01-01";
					dateEnd="2020-0101";
				}
				List list = null;
				try{	
				
			
			    	 list=orderService.findOrderDetailWithNoCheck(username,dateBegin,dateEnd);
			}catch(Exception e4){
				e4.printStackTrace();
			}	
			    	
				 model.addAttribute("username", username);	
				 model.addAttribute("detailList", list);
			 
			 
			 return "waitCheckd";
				}
	
		//已审核的订单
		@RequestMapping("/doneCheckd")
		public String zcPc1(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
			String username="绥阳店";
			String dateBegin=request.getParameter("dateBegin");
			String dateEnd=request.getParameter("dateEnd");
			if(dateBegin==null||dateBegin.equals("")){
				dateBegin="2000-01-01";
				dateEnd="2020-0101";
			}
			List list = null;
			
			
			//查询符合条件的订单数量
			TOrderExample example=new TOrderExample();
			list=orderService.findOrderDetailWithBeenCheck(username,dateBegin,dateEnd);
			 model.addAttribute("username", username);	
			 model.addAttribute("detailList", list);
			return "doneCheckd";
		}	
		//查看分店提交上来的信息
		@RequestMapping("/doingPc")
		public String doingPc(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
			List list=orderService.findOrderDoing();
			if(list.toString()=="[]"){
				return "error1";
			}
			
			model.addAttribute("detailList", list);
			return "doingPc";
		}
	//总店对提交审核的订单操作
		@RequestMapping("/chaPc")
		public String chaPc(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
			String picture=request.getParameter("picture");		
			List list=orderService.findOrderDetailWithTi(picture);
			if(list.toString()=="[]"){
				return "error1";
			}
	
			 TPay pay=TPayMapper.selectByPrimaryKey(2);
			 String payLi=pay.getSeller();
			 double payLi1=Double.parseDouble(payLi);
		
			 String total=orderService.findOrderDetailWithTi1(picture);
			 
			 model.addAttribute("picture", picture);
				model.addAttribute("total", total);
			 model.addAttribute("payLi1", payLi1);	
			model.addAttribute("detailList", list);
			return "chaPc";
		}
		
		//总店审核通过
	@RequestMapping("/shenHeTongGuo")
		public String shenHeTongGuo(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
			String trade=request.getParameter("trade");
			TIndexImgExample example=new TIndexImgExample();
			example.createCriteria().andPictureEqualTo(trade);
			List list= TIndexImgMapper.selectByExample(example);
			TIndexImg img=(TIndexImg) list.get(0);
			img.setLink("审核通过");
			TIndexImgMapper.updateByPrimaryKeySelective(img);
			List list1=orderService.findOrderDoing();
			if(list1.toString()=="[]"){
				return "error1";
			}
			
			model.addAttribute("detailList", list1);
			return "doingPc";
		}
	//总店审核驳回
@RequestMapping("/shenHeBoHui")
	public String shenHeBoHui(HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
		String trade=request.getParameter("trade");
		TIndexImgExample example=new TIndexImgExample();
		example.createCriteria().andPictureEqualTo(trade);
		List list= TIndexImgMapper.selectByExample(example);
		TIndexImg img=(TIndexImg) list.get(0);
		img.setLink("已驳回");
		TIndexImgMapper.updateByPrimaryKeySelective(img);
		List list1=orderService.findOrderDoing();
		if(list1.toString()=="[]"){
			return "error1";
		}
		
		model.addAttribute("detailList", list1);
		return "doingPc";
	}
}
